<template>
  <div class="h-full flex flex-col text-#fff justify-center">
    <div class="h-50px leading-50px text-20px text-center px-20px">title</div>
    <main class="overflow-hidden" :class="{ 'flex-1': dataSources.length }">
      <el-scrollbar ref="scrollRef">
        <div id="scroll-box" class="w-full max-w-screen-md m-auto">
          <div v-if="!dataSources.length" class="text-center p-20px">
            <div class="text-26px font-bold">我是 gemma3，很高兴见到你</div>
            <div class="text-14px mt-10px">
              我可以帮你写代码、读文件、写作各种创意内容，请把你的任务交给我吧~
            </div>
          </div>
          <div v-else>
            <Message
              v-for="(item, index) of dataSources"
              :key="index"
              :date-time="item.dateTime"
              :text="item.text"
              :reasoning="item.reasoning"
              :inversion="item.inversion"
              :error="item.error"
              :loading="item.loading"
            />
          </div>
        </div>
      </el-scrollbar>
    </main>
    <footer>
      <div class="py-20px max-w-screen-md m-auto">
        <div class="p-15px bg-#404045 rounded-24px">
          <div class="input-box">
            <el-input
              v-model="prompt"
              style="width: 100%"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              resize="none"
              placeholder="发送信息..."
            />
          </div>
          <div class="flex items-center justify-between">
            <div></div>
            <div class="flex item-center">
              <el-button
                v-if="loading"
                type="primary"
                :icon="CloseBold"
                circle
                @click="handleStop"
              />
              <el-button
                v-else
                type="primary"
                :icon="Position"
                :disabled="!prompt"
                circle
                @click="handleSubmit"
              />
            </div>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup lang="ts">
import { Position, CloseBold } from "@element-plus/icons-vue";
import { computed, onMounted, ref } from "vue";
import Message from "./components/Message/index.vue";
import { chatCompletions } from "@/api/chat.ts";
import { useChatStore } from "@/stores/modules/chat.ts";
import { useRoute } from "vue-router";
import { useScroll } from "./hooks/useScroll";
import { useChat } from "@/views/chat/hooks/useChat.ts";
import { useReadStream } from "@/views/chat/hooks/useReadStream.ts";
import type { ConversationMessage } from "@/types/chat.ts";
import { ss } from "@/utils/storage";
const route = useRoute();
let controller = new AbortController();

const { addChat, updateChat } = useChat();
const { scrollRef, scrollToBottom, scrollToBottomIfAtBottom } = useScroll();
console.log(scrollRef);
const chatStore = useChatStore();
const { handleStreamResponse } = useReadStream();
const { uuid } = route.params as { uuid: string };
// 输入框
const prompt = ref<string>("");
const loading = ref<boolean>(false);

const dataSources = computed(() => {
  console.log(chatStore.getChatByUuid(+uuid));
  return chatStore.getChatByUuid(+uuid);
});

async function handleSubmit() {
  if (!+uuid || +uuid === 0) {
    chatStore.addHistory({
      title: "新建会话",
      uuid: Date.now(),
      isEdit: false,
      visible: false,
    });
    ss.set("chatSubmitPrompt", prompt.value);
    return;
  }
  onConversation();
}

async function onConversation() {
  let message = prompt.value;
  if (loading.value) return;
  if (!message || message.trim() === "") return;
  controller = new AbortController();

  const conversationList = dataSources.value
    .filter((item) => item.text)
    .map(
      (item) =>
        ({
          role: item.inversion ? "user" : "assistant",
          content: item.text,
        } as ConversationMessage)
    );
  addChat(+uuid, {
    dateTime: new Date().toLocaleString(),
    text: message,
    inversion: true,
    error: false,
  });
  loading.value = true;
  prompt.value = "";

  addChat(+uuid, {
    dateTime: new Date().toLocaleString(),
    text: "",
    reasoning: "思考中...",
    loading: true,
    inversion: false,
    error: false,
  });
  try {
    const paramMsg = [];
    paramMsg.push({ role: "user", content: message });
    const resposne: any = await chatCompletions(controller.signal, paramMsg);
    await handleStreamResponse(resposne, (jsonData: any) => {
      const contentText = jsonData.message.content;
      if (contentText) {
        updateChat(+uuid, dataSources.value.length - 1, {
          text: contentText ?? "",
          inversion: false,
          error: false,
          loading: true,
        });
        scrollToBottomIfAtBottom();
      }
    });

    updateChat(+uuid, dataSources.value.length - 1, {
      inversion: false,
      error: false,
      loading: false,
    });
    loading.value = false;
    console.log("Stream ended");
  } catch (error) {
    console.log(error);
    loading.value = false;
    if (error instanceof DOMException && error.name === "AbortError") {
      updateChat(+uuid, dataSources.value.length - 1, {
        text: "\n\n用户手动中断。",
        inversion: false,
        error: false,
        loading: false,
      });
    } else {
      updateChat(+uuid, dataSources.value.length - 1, {
        text: "\n\n服务器异常，请稍后再试。",
        inversion: false,
        error: true,
        loading: false,
      });
    }
  }
}

function handleStop() {
  if (loading.value) {
    controller.abort();
    loading.value = false;
  }
}

onMounted(() => {
  if (!route.params.uuid) {
    chatStore.active = 1002;
  }

  const promptValue = ss.get("chatSubmitPrompt");
  if (promptValue) {
    prompt.value = promptValue;
    ss.set("chatSubmitPrompt", "");
    onConversation();
  }
});
</script>

<style scoped lang="scss">
.input-box {
  :deep(.el-textarea) {
    .el-textarea__inner {
      background-color: transparent;
      color: #fff;
      box-shadow: none;
      padding: 0;
      font-size: 16px;
    }
  }
}
</style>
